from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
import time
from bs4 import BeautifulSoup
import time
import re
import urllib


#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []
    # 获取sid并且更新返回
    soup = BeautifulSoup(response.text, "html5lib")

    lis = soup.select(".datalist tbody tr")


    for li in lis:
        tempData = resultData()

        try:
            tempData["titleName"] = li.select(".titleB p")[0].text.strip()
        except:
            pass
        try:
            tempData["titleHref"] = 'http://www.airitilibrary.cn'+li.select(".titleB p a")[0]["href"]
        except:
            pass
        try:
            tempData["author"] = [li.select(".titleB p")[1].text.strip()]
        except:
            pass
        try:
            tempData["source"] = li.select(".titleB p")[2].text.strip()
        except:
            pass
        allData.append(tempData)

    return allData

def getData(keyword):
    headers = {
        'Connection': 'keep-alive',
        'Pragma': 'no-cache',
        'Cache-Control': 'no-cache',
        'Origin': 'http://www.airitilibrary.cn',
        'Upgrade-Insecure-Requests': '1',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
        'Referer': 'http://www.airitilibrary.cn/Search/ArticleSearch?ArticlesViewModel_SearchField=cell&ArticlesViewModel_TitleKeywordsAbstract=&ArticlesViewModel_Author=&ArticlesViewModel_JournalBookDepartment=&ArticlesViewModel_ArticleArea_TaiwanHongKongMacao=false&ArticlesViewModel_ArticleArea_China=false&ArticlesViewModel_ArticleArea_American=false&ArticlesViewModel_ArticleArea_Other=false&PublicationsViewModel_SearchField=&PublicationsViewModel_PublicationName=&PublicationsViewModel_ISSN=&PublicationsViewModel_PublicationUnitName=&PublicationsViewModel_PublicationArea_TaiwanHongKongMacao=false&PublicationsViewModel_PublicationArea_China=false&PublicationsViewModel_PublicationArea_American=false&PublicationsViewModel_PublicationArea_Other=false',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('ArticlesViewModel_SearchField', keyword),
        ('ArticlesViewModel_TitleKeywordsAbstract', ''),
        ('ArticlesViewModel_Author', ''),
        ('ArticlesViewModel_JournalBookDepartment', ''),
        ('ArticlesViewModel_ArticleArea_TaiwanHongKongMacao', 'false'),
        ('ArticlesViewModel_ArticleArea_China', 'false'),
        ('ArticlesViewModel_ArticleArea_American', 'false'),
        ('ArticlesViewModel_ArticleArea_Other', 'false'),
        ('PublicationsViewModel_SearchField', ''),
        ('PublicationsViewModel_PublicationName', ''),
        ('PublicationsViewModel_ISSN', ''),
        ('PublicationsViewModel_PublicationUnitName', ''),
        ('PublicationsViewModel_PublicationArea_TaiwanHongKongMacao', 'false'),
        ('PublicationsViewModel_PublicationArea_China', 'false'),
        ('PublicationsViewModel_PublicationArea_American', 'false'),
        ('PublicationsViewModel_PublicationArea_Other', 'false'),
    )


    response = requests.post('http://www.airitilibrary.cn/Search/ArticleSearch', headers=headers, params=params)

    allData = formData(response)

    return allData


def index(request):

    data = json.loads(request.POST.get('data', '1'))

    allData= getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")
